package com.handpay.zztong.hp.login.activity;

import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.Toast;

import com.handpay.crypto.Caesar;
import com.handpay.framework.ClientEngine;
import com.handpay.framework.HttpEngine;
import com.handpay.framework.LuaTableUtil;
import com.handpay.framework.SecureManager;
import com.handpay.framework.utils.CommonUtils;
import com.handpay.framework.utils.DES2PWD;
import com.handpay.zztong.hp.R;
import com.handpay.zztong.hp.base.activity.ZZTongActivity;
import com.handpay.zztong.hp.bean.ResponseBean;
import com.handpay.zztong.hp.login.bill.AuthCodeBill;
import com.handpay.zztong.hp.login.model.UserRegisterBean;
import com.handpay.zztong.hp.main.activity.MainActivity;
import com.handpay.zztong.hp.other.activity.ShowHtmlActivity;
import com.handpay.zztong.hp.ZZTApplication;
import com.handpay.zztong.hp.bean.ActionBar;
import com.handpay.zztong.hp.config.ZZTConfig;
import com.handpay.zztong.hp.config.ZZTConstant;
import com.handpay.zztong.hp.log.HPLog;
import com.handpay.zztong.hp.protocol.BaseProtocolKey;
import com.handpay.zztong.hp.ui.VerificationCodeButton;
import com.handpay.zztong.hp.utils.AccountUtils;

import java.util.Hashtable;

import se.krka.kahlua.vm.LuaTable;

public class RegisterActivity extends ZZTongActivity implements OnClickListener {

    private EditText accountEditText;

    private EditText passwordEditText;

    private EditText confirmPWDEditText;
    private EditText phoneEditText;
    private EditText verifyCodeEditText;

    private VerificationCodeButton sendVerifycodeButton;
    private Button registerButton;
    private CheckBox checkbox_agree_register;

    private String account;
    private String phone;
    private String password;
    private String confirmPassword;
    private String verifyCode;
    private AuthCodeBill authCodeBill;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        this.setContentView(R.layout.activity_register);
        super.onCreate(savedInstanceState);

        this.accountEditText = (EditText) findViewById(R.id.editText_account);
        this.passwordEditText = (EditText) findViewById(R.id.editText_password);
        this.confirmPWDEditText = (EditText) findViewById(R.id.editText_confirm_password);
        this.phoneEditText = (EditText) findViewById(R.id.editText_phone);
        this.verifyCodeEditText = (EditText) findViewById(R.id.editText_SMS_verifyCode);

        findViewById(R.id.user_register_service_btn).setOnClickListener(this);

        this.sendVerifycodeButton = (VerificationCodeButton) findViewById(R.id.button_send_verifycode);
        this.sendVerifycodeButton.setOnClickListener(this);
        this.registerButton = (Button) findViewById(R.id.registerButton);
        this.registerButton.setOnClickListener(this);
        checkbox_agree_register = (CheckBox) findViewById(R.id.checkbox_agree_register);
        authCodeBill = new AuthCodeBill(this);
    }

    @Override
    public void onClick(View v) {
        int i = v.getId();
        if (i == R.id.button_send_verifycode) {
            phone = phoneEditText.getText().toString();
            if (TextUtils.isEmpty(phone)) {
                Toast.makeText(this, R.string.siguture_phone, Toast.LENGTH_SHORT).show();
            } else if (!CommonUtils.isMobileNum(phone)) {
                Toast.makeText(this, R.string.input_right_phone_tip, Toast.LENGTH_SHORT).show();
            } else {
                authCodeBill.sendAuthCode(ZZTConstant.AUTHCODE_ACTION_REG, phone);
                sendVerifycodeButton.startLocker(-1);
            }

        } else if (i == R.id.user_register_service_btn) {
            Intent intent = new Intent(this, ShowHtmlActivity.class);
            intent.putExtra(ShowHtmlActivity.ShowHtml_Title_Key, getString(R.string.zzt_user_register));
            intent.putExtra(ShowHtmlActivity.ShowHtml_Html_Path_Key, ZZTConfig.HPZZT_URL);
            this.startActivity(intent);

        } else if (i == R.id.registerButton) {
            account = accountEditText.getText().toString();
            password = passwordEditText.getText().toString();
            confirmPassword = confirmPWDEditText.getText().toString();
            phone = phoneEditText.getText().toString();
            verifyCode = verifyCodeEditText.getText().toString();
            if (TextUtils.isEmpty(account)) {
                Toast.makeText(this, R.string.no_input_account, Toast.LENGTH_SHORT).show();
                return;
            }
            if (!AccountUtils.isAccountLegal(account)) {
                Toast.makeText(this, R.string.illegal_input_account, Toast.LENGTH_SHORT).show();
                return;
            }
            if (TextUtils.isEmpty(password)) {
                Toast.makeText(this, R.string.no_input_password, Toast.LENGTH_SHORT).show();
                return;
            }
            if (!AccountUtils.isPWDLegal(password, AccountUtils.PWD_MIN_LEN)) {
                Toast.makeText(this, R.string.illegal_input_password, Toast.LENGTH_SHORT).show();
                return;
            }
            if (TextUtils.isEmpty(confirmPassword)) {
                Toast.makeText(this, R.string.sure_input_password, Toast.LENGTH_SHORT).show();
                return;
            }

            if (!AccountUtils.isPWDLegal(confirmPassword, AccountUtils.PWD_MIN_LEN)) {
                Toast.makeText(this, R.string.illegal_input_password, Toast.LENGTH_SHORT).show();
                return;
            }
            if (!password.equals(confirmPassword)) {

                Toast.makeText(this, R.string.input_error_reset_zzt_pwd_tip, Toast.LENGTH_SHORT).show();
                return;
            }

            if (TextUtils.isEmpty(phone)) {
                Toast.makeText(this, R.string.siguture_phone, Toast.LENGTH_SHORT).show();
                return;
            } else if (!CommonUtils.isMobileNum(phone)) {
                Toast.makeText(this, R.string.input_right_phone_tip, Toast.LENGTH_SHORT).show();
                return;
            }

            if (TextUtils.isEmpty(verifyCode)) {
                Toast.makeText(this, R.string.no_input_verifycode, Toast.LENGTH_SHORT).show();
                return;
            }
            if (!checkbox_agree_register.isChecked()) {
                Toast.makeText(this, R.string.no_agreement, Toast.LENGTH_SHORT).show();
                return;
            }
            if (password.equals(confirmPassword)) {
                doRegister();
            }
            return;
        }
        super.onClick(v);
    }

    @Override
    public ActionBar getActivityActionBar() {
        //leftBar goBack();
        return new ActionBar(this.getString(R.string.register_title), true);
    }

    private void doRegister() {
        Hashtable<String, String> params = new Hashtable<String, String>();
        params.put(BaseProtocolKey.ACCOUNT, SecureManager.getInstance().des(account, 1, null));
        params.put("pwd", SecureManager.getInstance().des(password, 1, null));
        params.put("action", ZZTConstant.AUTHCODE_ACTION_REG);
        params.put("verifyCode", verifyCode);
        params.put(BaseProtocolKey.PHONE, SecureManager.getInstance().des(phone, 1, null));
        params.put(BaseProtocolKey.CHANNEL, ClientEngine.CHANNEL);
        doJsonPost(this, Do_Register, UserRegisterBean.class, params);
    }

    @Override
    public boolean netJsonResponse(final String action, ResponseBean resp, boolean showAlert) {
        boolean bResult = super.netJsonResponse(action, resp, showAlert, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                if (action.equals(Do_SendPhoneCode)) {
                    sendVerifycodeButton.cancelLocker();
                }
                dialog.dismiss();
            }
        });
        if (bResult) {
            return true;
        }
        if (action.equals(Do_SendPhoneCode)) {
            if (resp.getResponseCode().equals("0")) {
                Toast.makeText(RegisterActivity.this, "发送验证码成功！", Toast.LENGTH_SHORT).show();
            } else {
                showAlertDialog(RegisterActivity.this, getString(R.string.prompt), resp.getErrMessage());
            }
        } else if (action.equals(Do_Register)) {
            UserRegisterBean userRegisterBean = (UserRegisterBean) resp;
            if (resp.getResponseCode().equals("0")) {
                String userId = SecureManager.getInstance().des(CommonUtils.objectToString(userRegisterBean.getUserID()), 0, null);
                AccountUtils.saveAccount(this, account, phone, AccountUtils.AccountStatus.NOUPLOAD, "", userRegisterBean.getMerchantCode(), userId);
                //保存到本地账号密码
                AccountUtils.saveRMSAccountName(account);
                String afterPwd = Caesar.caesarEncryption(password);
                try {
                    AccountUtils.saveRMSAccountPWD(DES2PWD.encryptDES(afterPwd, ZZTConfig.SECRETKEY));
                } catch (Exception e) {
                    HPLog.e(HPLog.SSX_TAG, "保存用户密码异常");
                    e.printStackTrace();
                }
                //如果注册成功默认表示已经同意用户协议
                ClientEngine.getInstance().saveRMSData(ClientEngine.KEY_CLIENT_AGREEMENT + AccountUtils.getAccountName(this), "1");
                Intent intent = new Intent(this, RegisterResultActivity.class);
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
                intent.putExtra(BaseProtocolKey.ACCOUNT, account);
                intent.putExtra(BaseProtocolKey.PHONE, phone);
                this.startActivity(intent);
            } else {
                showAlertDialog(RegisterActivity.this, getString(R.string.prompt), userRegisterBean.getErrMessage());
            }
        }
        return true;
    }

    @Override
    public boolean netResponse(String action, Hashtable<String, Object> resp, boolean showAlert) {
        boolean result = super.netResponse(action, resp, showAlert);
        if (action.equals(Do_SendPhoneCode)) {
            if (result) {
                sendVerifycodeButton.cancelLocker();
                return true;
            }
        } else if (action.equals(Do_Register)) {
            if (result) {
                return result;
            }
            int responseCode = -1;
            try {
                byte data[] = (byte[]) resp.get(HttpEngine.Key_RespData);
                LuaTable luaTable = LuaTableUtil.stringToLuaTable(data, isDataCompile);
                responseCode = CommonUtils.objectToInt(luaTable.rawget("responseCode"));
                if (responseCode == 0) {
                    this.finish();
                    ZZTApplication.getApp().exitApp();
                    AccountUtils.saveAccount(this, account, phone, AccountUtils.AccountStatus.NOUPLOAD, "", null, null);
                    //保存到本地账号密码
                    AccountUtils.saveRMSAccountName(account);
                    String afterPwd = Caesar.caesarEncryption(password);
                    AccountUtils.saveRMSAccountPWD(DES2PWD.encryptDES(afterPwd, ZZTConfig.SECRETKEY));

                    Intent intent = new Intent(this, RegisterResultActivity.class);
                    intent.putExtra(BaseProtocolKey.ACCOUNT, account);
                    intent.putExtra(BaseProtocolKey.PHONE, phone);
                    this.startActivity(intent);
                    return true;
                } else {
                    String errMessage = CommonUtils.objectToString(luaTable.rawget("errMessage"));
                    showAlertDialog(RegisterActivity.this, getString(R.string.prompt), errMessage);
                    return false;
                }
            } catch (Exception e) {
                HPLog.e("RegisterActivity", "", e);
                return true;
            }
        }
        return false;
    }

    @Override
    protected boolean isShownTabs() {
        return false;
    }
}
